﻿using Growatt.Component.Cls;
using Growatt.CreateXLXFormWordRootobject;
using Growatt.ShinebusServiceUploadPack.Service.OSS.Model;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace Growatt.ShinebusServiceUploadPack.Service.FeishuHelper
{
  
    public class FileUploadUtils : BaseHttpClient
    {
      
        public FileUploadUtils(IHttpClientFactory httpClientFactory,string urlUploadFileFieshuUrl) : base(httpClientFactory, urlUploadFileFieshuUrl)
        {
        }

        public FileUploadUtils(IHttpClientFactory httpClientFactory, ILogger<FileUploadUtils> logger, string urlUploadFileFieshuUrl) : base(httpClientFactory, urlUploadFileFieshuUrl)
        {
        }

        public async Task InsertServerOnlyOneFileAsync(string urlUploadFileFieshuUrl,FieldsFileUploadRecordShinebusUtils query, ILogger logger)
        {
            UpdateIDs(urlUploadFileFieshuUrl);
            var apiHelper = new FeishuAPIHelper();
            accessToken = await apiHelper.GetTenantAccessToken();

            // 创建实体对象
            var recordBody = new RecordBodyFileShinebusUploadUploadUtils
            {
                Fields = query,
            };

            // 将实体对象序列化为JSON字符串
            string jsonBody = JsonConvert.SerializeObject(recordBody);
            var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");

            // 定义请求地址
            string url = $"{BaseAddress}bitable/v1/apps/{baseID}/tables/{tablesID}/records?ignore_consistency_check=true&user_id_type=open_id";

            // 发送 POST 请求
            await SendPostRequestAsync(url, content, logger, accessToken);
        }
        public async Task<string> upload_OnlyOneFileAsynchronous(string filePath, ILogger logger)
        {
            UpdateIDs(urlUploadFileFieshuUrl);
            var apiHelper = new FeishuAPIHelper();
            accessToken = await apiHelper.GetTenantAccessToken();
            // 定义请求地址
            string url = "https://open.feishu.cn/open-apis/drive/v1/medias/upload_all";

            // 准备文件和元信息
            string fileName = Path.GetFileName(filePath); // 文件名
            string parentType = "bitable_file"; // 父类类型
            //string parentType = "bitable_image"; // 父类类型
            string parentNode = baseID; // 点位 token
            string extra = baseID; // 附加信息
            int fileSize = (int)new FileInfo(filePath).Length; // 文件大小

            using (HttpClient httpClient = _httpClientFactory.CreateClient("OSS"))
            {
                // 设置请求头
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                // 创建 MultipartFormDataContent（多部分请求内容）
                var content = new MultipartFormDataContent();

                // 添加文件字段
                var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                var fileContent = new StreamContent(fileStream);
                fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                content.Add(fileContent, "file", fileName);

                // 添加其他字段
                // 文件名
                content.Add(new StringContent(fileName), "file_name");
                // 父类类型
                content.Add(new StringContent(parentType), "parent_type");
                // 父节点
                content.Add(new StringContent(parentNode), "parent_node");
                // 文件大小
                content.Add(new StringContent(fileSize.ToString()), "size");
                // 附加信息
                content.Add(new StringContent(extra), "extra");

                // 发送 POST 请求
                try
                {
                    var response = await httpClient.PostAsync(url, content);
                    string responseContent = await response.Content.ReadAsStringAsync();

                    if (response.IsSuccessStatusCode)
                    {
                        Console.WriteLine("文件上传成功:");
                        var responseObject = JsonConvert.DeserializeObject<ApiResponse_upload_all>(responseContent);
                        var file_tokenStr = responseObject.data.file_token;

                        return file_tokenStr;
                    }
                    else
                    {
                        Console.WriteLine($"上传失败，状态码：{response.StatusCode}");
                    }

                    Console.WriteLine(responseContent);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"上传过程出错：{ex.Message}");
                    return string.Empty;
                }
                finally
                {
                    fileStream.Dispose();
                }
            }
            return string.Empty;

        }
        public async Task<int> UpdateServerAsync(string urlUploadFileFieshuUrl, RecordFieldsFileUploadShinebusUtilsBody recordBody, string recordId, ILogger logger)
        {
            UpdateIDs(urlUploadFileFieshuUrl);
            var apiHelper = new FeishuAPIHelper();
            accessToken = await apiHelper.GetTenantAccessToken();

            // 将实体对象序列化为JSON字符串
            string jsonBody = JsonConvert.SerializeObject(recordBody);
            var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");

            // 定义请求地址
            string url = $"{BaseAddress}bitable/v1/apps/{baseID}/tables/{tablesID}/records/{recordId}";

            // 发送 PUT 请求
            string responseContent = await SendPutRequestAsync(url, content, logger, accessToken);

            if (!string.IsNullOrEmpty(responseContent))
            {
                var updateResponse = JsonConvert.DeserializeObject<UpdateResponse>(responseContent);
                if (updateResponse != null)
                {
                    return updateResponse.Code;
                }
            }
            return -1;
        }

        // 实体类定义
        #region 实体类

        public class FieldsFileUploadUtils
        {
            public List<AttachmentItemFileUploadUtils> 升级前运行版本 { get; set; }
            public string 设备型号 { get; set; }
            public string 升级后目标版本 { get; set; }
            public string 更新日志 { get; set; }
            public string 上传正式服务器 { get; set; }
            public double 更新日期 { get; set; }
        }

        public class AttachmentItemFileUploadUtils
        {
            public string file_token { get; set; }
        }

        public class RecordBodyFileUploadUtils
        {
            public FieldsFileUploadUtils Fields { get; set; }
        }
        public class RecordFieldsFileUploadUtilsBody
        {
            public FieldsFileUploadUtils fields { get; set; }
        }

        public class RecordFieldsFileUploadShinebusUtilsBody
        {
            public FieldsFileUploadRecordShinebusUtils fields { get; set; }
        }
        public class FieldsFileUploadRecordShinebusUtils
        {
            public string 新的文件夹的名称 { get; set; }
            public string 上传文件成功的ID { get; set; }
            public string 审核通过的云端路径 { get; set; }
            public string 设备型号 { get; set; }
            public string 设备类型 { get; set; }
            public string 产品类型 { get; set; }
            public string softType { get; set; }
            public string 是否审核 { get; set; }
            public string 具体操作时间 { get; set; }
        }

        public class RecordBodyFileShinebusUploadUploadUtils
        {
            public FieldsFileUploadRecordShinebusUtils Fields { get; set; }
        }

        public class RecordFileUploadUtils
        {
            public FieldsFileUploadUtils Fields { get; set; }
            public string id { get; set; }
            public string record_id { get; set; }
        }

        public class DataFileUploadUtils
        {
            public RecordFileUploadUtils Record { get; set; }
        }

        public class ApiResponseUploadAll
        {
            public int Code { get; set; }
            public DataFileUploadUtils Data { get; set; }
            public string Msg { get; set; }
        }

        public class UpdateResponse
        {
            public int Code { get; set; }
            public string Msg { get; set; }
        }

        #endregion
    }

}
